<?php

namespace Home\Controller;

class UserController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_Member_mod = M("Member");
        $this->_user_id = session('visitor.user_id');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=index 用户信息接口
     */
    function index() {
        $user_info = M('member')->where('user_id=' . $this->_user_id)->find();
        $user_info['ugrade'] = D('member')->get_grade_info($this->_user_id);
        if (!$user_info) {
            render('10106', '用户不存在');
        }
        unset($user_info['password']);
        unset($user_info['zf_pass']);
        $resBanner = M('banner_setting')->where(array('type_id' => 4))->order('sort_order')->limit(5)->select();
        $data['banner'] = $resBanner;
        //获取订单数目信息
        $data['pending'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_PENDING . "'")->count("order_id");
        $data['accepted'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_ACCEPTED . "'")->count("order_id");
        $data['shipped'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_SHIPPED . "'")->count("order_id");
        $data['finished'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_FINISHED . "' AND evaluation_status = 0")->count("order_id");
        render('10000', '', array_merge(array('order' => $data), $user_info));
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=profile 显示用户基本信息
     * 
     */
    function profile() {
        if (!IS_POST) {
            $member = $this->_Member_mod->where('user_id=' . $this->_user_id)->find();
            $textarea = M('textarea')->find();
            render('10000', '获取用户信息成功', array(
                'member' => $member,
                'textarea'=>$textarea['member']
            ));
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=profile_edit 编辑用户基本信息
     * @apiName 编辑用户基本信息
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 编辑用户基本信息
     * 
     * @apiParam {String} real_name 真实姓名
     * @apiParam {String} gender 性别
     * @apiParam {String} birthday 生日
     * @apiParam {String} im_msn MSN帐号
     * @apiParam {String} im_qq QQ帐号
     */
    function profile_edit() {
        if (IS_POST) {
            $data = array(
                'real_name' => I('post.real_name', ''),
//                lichen 2019/6/5 start
                'user_no' => I('post.user_no', ''),
//                lichen 2019/6/5 end
                'gender' => I('post.gender', ''),
//                'birthday' => I('post.birthday', ''),
                'im_msn' => I('post.im_msn', ''),
                'im_qq' => I('post.im_qq', ''),
            );
            $this->_Member_mod->where('user_id=' . $this->_user_id)->save($data);
            render('10000', '编辑成功');
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=password 设置用户登录密码
     * @apiName 设置用户登录密码
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 设置用户登录密码
     * 
     * @apiParam {String} orig_password 原密码
     * @apiParam {String} new_password 新密码
     * @apiParam {String} confirm_password 再次输入新密码
     * 
     */
    function password() {
        if (IS_POST) {
            $orig_password = I('post.orig_password', '');
            $new_password = I('post.new_password', '');
            $confirm_password = I('post.confirm_password', '');
            if ($new_password != $confirm_password) {
                render('10102', '输入两次密码不一致！');
            }
            if (!$new_password) {
                render('10105', '新密码为空！');
            }
            $passlen = strlen($new_password);
            if ($passlen < 6 || $passlen > 20) {
                render('10104', '密码长度必须大于6位！');
                return;
            }
            D("Member")->do_edit($this->_user_id, $orig_password, array('password' => $new_password));
            render('10000', '修改密码成功');
        }
    }
    
    

    /**
     * @api {post} /index.php?m=Home&c=User&a=mobile_edit 修改绑定手机
     * @apiName 修改绑定手机
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 修改绑定手机
     * 
     * @apiParam {String} msg_sign 短信签名
     * @apiParam {String} phone_mob 新手机
     * @apiParam {String} msg_code 验证码
     * 
     */
    function mobile_edit() {
        $msg_sign = I('request.msg_sign', '');
        $phone_mob = I('request.phone_mob', '');
        $msg_code = I('request.msg_code', '');
        if (empty($msg_sign) || empty($msg_code) || empty($phone_mob)) {
            render('10001', '缺少参数');
        }
        if (md5('send_message_change' . $msg_code) != $msg_sign) {
            render('10016', '短信验证码错误');
        }
        //判断此手机是否被绑定
        $member = M('member')->where('phone_mob=' . $phone_mob)->find();
        if(!empty($member)){
            render('19999', '对不起此手机已经被绑定');
        }
        $result = M('Member')->where('user_id=' . $this->_user_id)->save(array('phone_mob' => $phone_mob));
        if($result){
            render('10000', '修改支付密码成功');
        }else{
            render('19999', '修改支付密码失败');
        }
    }

    /**
     * 
     * @api {get} /index.php?m=Home&c=User&a=send_message_change 发送修改绑定手机的短信
     * @apiName 发送修改绑定手机的短信
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 发送修改绑定手机的短信
     * 
     * @apiParam {String} msg_sign 短信签名
     */
    function send_message_change() {
        //传phone_mob 表示发送到指定手机号中
        $mobile = I('request.phone_mob', '');
        if (!empty($mobile)) {
            if (!preg_match("/^1[34578]{1}\d{9}$/", $mobile)) {
                render('10069', '绑定手机号格式错误!');
            }
        } else {
            $member = M('member')->where('user_id=' . $this->_user_id)->find();
            $mobile = $member['phone_mob'];
            if (!$mobile) {
                render('10012', '手机号码为空');
            }
        }
        D('Msglog')->send_msg_system('change', $mobile);
        $msg_sign = md5('send_message_change' . $_SESSION['MobileConfirmCode']);
        render('10000', '短信发送成功!', array('msg_sign' => $msg_sign));
    }
    
    
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_goods_list 显示收藏的商品列表
     * @apiName 显示收藏的商品列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示收藏的商品列表
     * 
     * @apiSuccess {String} goods_id 商品ID
     * @apiSuccess {String} default_image 商品图片
     * @apiSuccess {String} goods_name 商品名称
     * @apiSuccess {String} price 价格
     * @apiSuccess {String} add_time 收藏时间
     */
    function favorite_goods_list() {
        $map['user_id'] = $this->_user_id;
        $map['collect.type'] = 'goods';
        $goods_mod = M("goods");
        $goods_list = $goods_mod->where($map)
                ->field('goods_id,default_image,goods_name,price,collect.add_time')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'collect as collect ON item_id = goods_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        if($goods_list){
            foreach ($goods_list as $key => $goods) {
                $goods_list[$key]['add_time'] = date('Y-m-d H:i:s',$goods['add_time']);
            }
        }
        render('10000', '获取收藏商品成功', array(
            'goods_list' => $goods_list
        ));
    }
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_add 新增收藏的商品
     * @apiName 新增收藏的商品
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增收藏的商品
     * 
     * @apiParam {String} item_id 商品ID
     */
    function favorite_goods_add() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'goods';
        if ($collect_mod->where($map)->find()) {
            $collect_mod->where($map)->delete();
            render('10000', '删除商品成功');
        }
        $map['add_time'] = time();
        $collect_mod->add($map);
        render('10000', '收藏商品成功');
    }
    
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_goods_del 删除收藏的商品
     * @apiName 删除收藏的商品
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除收藏的商品
     * 
     * @apiParam {String} item_id 收藏ID
     * 
     */
    function favorite_goods_del() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('16666', '参数错误');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'goods';
        $collect_mod->where($map)->delete();
        render('10000', '删除收藏商品成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_list 显示收藏的店铺列表
     * @apiName 显示收藏的店铺列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示收藏的店铺列表
     * 
     * @apiSuccess {String} store_id 店铺ID
     * @apiSuccess {String} store_logo 店铺LOGO
     * @apiSuccess {String} store_name 店铺名称
     * @apiSuccess {String} owner_name 拥有者名称
     * @apiSuccess {String} add_time 收藏时间
     * 
     */
    function favorite_store_list() {
        $map['user_id'] = $this->_user_id;
        $map['collect.type'] = 'store';
        $store_mod = M("store");
        $store_list = $store_mod->where($map)
                ->field('store_id,store_logo,store_name,owner_name,collect.add_time')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'collect as collect ON item_id = store_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        
        if($store_list){
            foreach ($store_list as $key => $store) {
                $store_list[$key]['add_time'] = date('Y-m-d H:i:s',$store['add_time']);
            }
        }
        
        render('10000', '获取收藏店铺成功', array(
            'store_list' => $store_list,
        ));
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_add 新增收藏的店铺
     * @apiName 新增收藏的店铺
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增收藏的店铺
     * 
     * @apiParam {String} item_id 店铺ID
     * 
     */
    function favorite_store_add() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'store';
        if ($collect_mod->where($map)->find()) {
            render('10121', '已收藏过该店铺');
        }
        $map['add_time'] = time();
        $collect_mod->add($map);
        render('10000', '收藏店铺成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_del 删除收藏的店铺
     * @apiName 删除收藏的店铺
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除收藏的店铺
     * 
     * @apiParam {String} item_id 店铺ID
     * 
     */
    function favorite_store_del() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'store';
        $collect_mod->where($map)->delete();
        render('10000', '删除收藏店铺成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=address_list 显示用户地址列表
     * @apiName 显示用户地址列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示用户地址列表
     * 
     * @apiSuccess {String} addr_id 地址ID
     * @apiSuccess {String} user_id 用户ID
     * @apiSuccess {String} consignee 收货人
     * @apiSuccess {String} region_id 地区ID
     * @apiSuccess {String} region_name 地区名称
     * @apiSuccess {String} address 详细地址
     * @apiSuccess {String} zipcode 邮政编码
     * @apiSuccess {String} phone_mob 联系手机
     * @apiSuccess {String} is_default 是否为默认地址1为是  0 为否 
     */
    function address_list() {
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $address_list = $address_mod
                ->where($map)
                ->order('is_default desc')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        $textarea = M('textarea')->find();
        render('10000', '获取地址列表成功', array(
            'address_list' => $address_list,
            'textarea' => $textarea['address']
        ));
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=address_add 新增地址
     * @apiName 新增地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增地址
     * 
     * @apiParam {String} consignee 收货人
     * @apiParam {String} region_id 地区ID
     * @apiParam {String} region_name 地区名称
     * @apiParam {String} address 详细地址
     * @apiParam {String} zipcode 邮政编码
     * @apiParam {String} phone_mob 联系手机
     * 
     */
    function address_add() {
        if (IS_POST) {
            $data = array(
                'user_id' => $this->_user_id,
                'consignee' => I('post.consignee'),
                'region_id' => I('post.region_id'),
                'region_name' => I('post.region_name'),
                'user_no' => I('post.user_no'),
                'address' => I('post.address'),
                'zipcode' => I('post.zipcode'),
                'phone_mob' => I('post.phone_mob'),
            );
            $address_mod = M("address");
            $address_mod->data($data)->add();
            render('10000','新增成功');
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=address_edit 编辑地址
     * @apiName 编辑地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 编辑地址
     * 
     * @apiParam {String} addr_id 地址ID
     * @apiParam {String} consignee 收货人
     * @apiParam {String} region_id 地区ID
     * @apiParam {String} region_name 地区名称
     * @apiParam {String} address 详细地址
     * @apiParam {String} zipcode 邮政编码
     * @apiParam {String} phone_mob 联系手机
     * 
     */
    function address_edit() {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;

        $address = $address_mod->where($map)->find();
        if (empty($address)) {
            render('16666', '地址不存在');
        }

        if (IS_POST) {
            if(!$this->is_idcard(I('post.user_no'))){
                render('16666', '身份证号格式错误');
            }
            $data = array(
                'consignee' => I('post.consignee'),
                'region_id' => I('post.region_id'),
                'region_name' => I('post.region_name'),
                'address' => I('post.address'),
                'user_no' => I('post.user_no'),
                'zipcode' => I('post.zipcode'),
                'phone_mob' => I('post.phone_mob'),
            );
            $address_mod->where($map)->save($data);
            render('10000', '修改地址成功');
        } else {
            render('10000', '获取地址成功', array('address' => $address));
        }
    }
    /**
     * @api {post} /index.php?m=Home&c=User&a=set_default_address 设置默认收货地址
     * @apiName 设置默认收货地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 设置默认收货地址
     * 
     * @apiParam {String} addr_id 地址ID
     */
    function set_default_address()
    {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;
        
        $address_mod->where("user_id=" . $this->_user_id)->save(array('is_default'=>0));
        $address_mod->where("addr_id = {$addr_id} AND user_id=" . $this->_user_id)->save(array('is_default'=>1));
        render('10000', '设置默认地址成功');
    }
    /**
     * @api {post} /index.php?m=Home&c=User&a=address_del 删除地址
     * @apiName 删除地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除地址
     * 
     * @apiParam {String} addr_id 地址ID
     */
    function address_del() {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;
        $address = $address_mod->where($map)->find();
        if (empty($address)) {
            render('16666', '地址不存在');
        } else {
            $address_mod->where($map)->delete();
            render('10000', '');
        }
    }

//    lichen 2019/5/27 start
    function upload_portrait(){
        if(empty($_POST['user_id']) || empty($_POST['portrait'])){
            render('16666', '参数错误');
        }
        $url = M('Member')->where(array('user_id'=>$_POST['user_id']))->getField('portrait');
        if($url){
            $filename = './'.$url;
            unlink($filename);
        }
        $image = $_POST['portrait'];
        $imageName = date("YmdHis", time()) . rand(1000,10000) .'.jpg';
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }
        $path = BASE_PATH.'/data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'];
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $r = file_put_contents($path.'/'.$imageName, base64_decode($image));//返回的是字节数
        if (!$r) {
            render('16666', '图片生成失败');
        }else{
            $res = M('member')->where(array('user_id'=>$_POST['user_id']))->save(array('portrait'=>'data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'].'/'.$imageName));
            if(!$res){
                render('16666', '上传失败');
            }
            render('10000', '图片生成成功',array('portrait'=>'data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'].'/'.$imageName));
        }
    }

    function is_idcard( $id ){
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                } //phpfensi.com
                else
                {
                    return TRUE;
                }
            }
        }

    }


}

